package com.dingding.study.service.责任链模式.payImpl;

import com.dingding.study.service.责任链模式.PayHandler;
import com.dingding.study.service.责任链模式.pay.AliaPayHandler;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class PayHandlerChain implements ApplicationContextAware, InitializingBean {

    private ApplicationContext applicationContext;

    private PayHandler handle;

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, PayHandler> beansOfTypeMap = applicationContext.getBeansOfType(PayHandler.class);

        if (MapUtils.isEmpty(beansOfTypeMap)) {
            return;
        }
        List<PayHandler> handlers = new ArrayList<>(beansOfTypeMap.values());
        //这里相当于一个把所有的被注解标注过的对象，当做一个链表串起来
        for (int i = 0; i < handlers.size(); i++) {
            PayHandler payHandler = handlers.get(i);
            if (i < handlers.size() - 1) {
                payHandler.setNext(handlers.get(i + 1));
            }
        }
        handle = handlers.get(0);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    public String pay(String code){
        return handle.pay(code);
    }
}
